package com.dmcloud.zuul.config;

import com.dmcloud.common.util.reponse.ResponseConstant;
import com.dmcloud.common.util.reponse.ResultMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xiaodao
 * date: 2020/3/29
 * 权限校验失败
 */
@Component
@Slf4j
public class GatewayAccessDeniedHandler extends OAuth2AccessDeniedHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        log.info("权限校验失败");
        request.setAttribute("updateLog","yes");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        String json = objectMapper.writeValueAsString(ResultMessage.errorMsg(ResponseConstant.FORBIDDEN,"令牌校验失败！"));
        response.getWriter().write(json);
        response.getWriter().flush();
    }
}
